<?php
/**
 * Created by PhpStorm.
 * User: songdewei
 * Date: 2017/10/10
 * Time: 下午3:29
 */

namespace App\WeChat\WxApi;

use App\WeChat\WxApi\Message\WxCustomMessage;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class WxCustomMessageApi extends WxApi
{
    /**
     * 发送模板消息
     * @param WxCustomMessage $message
     * @return \Psr\Http\Message\StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public static function sendMessage(WxCustomMessage $message){
        if (!$message->getTouser()){
            throw new \Exception('Empty touser value', 1);
        }

        if (!$message->getMsgtype()){
            throw new \Exception('Empty msgtype value', 2);
        }

        if (!$message->getParams()){
            throw new \Exception('Empty params value', 3);
        }

        $uri = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".self::getAccessToken();
        $request = new Request('POST', $uri, [], $message->getMsgContent());
        $client = new Client();
        $response = $client->send($request);

        if ($response->getStatusCode() == 200) {
            return $response->getBody();
        } else {
            throw new \Exception('request failed', $response->getStatusCode());
        }
    }
}
